package initter

import (
	"MxShop/global"
	"MxShop/proto"
	"fmt"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func InitSrvGrpc() {
	//使用consule的过滤方法 从consule中直接拿到rpc端的服务信息
	result, err := global.ConsuleClient.Agent().ServicesWithFilter(fmt.Sprintf(`Service == "%s"`, global.ServerConfig.UserSrvConfig.Name))
	//将grpc封装成全局调用（之前是单个接口调用）
	//定义RPC端IP和port
	//userSrvIP := global.ServerConfig.SrvIP
	//userSrvPort := global.ServerConfig.SrvPort
	userSrvIp := ""
	userPort := 0
	for _, value := range result {
		userSrvIp = value.Address
		userPort = value.Port
		break
	}
	//如果没有取到rpc端服务的host地址 那么直接输出错误
	if userSrvIp == "" {
		zap.S().Info("链接用户rpc端失败", err)
		panic(err)
	}
	userClient, err := grpc.Dial(fmt.Sprintf("%s:%d", userSrvIp, userPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
	userSrvClient := proto.NewUserClient(userClient)
	global.UserClient = userSrvClient
}
